const api = require("../../../api/sop");
import { err, toast, to } from "../../../utils/wxapi";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    list: {},
    id: "",
    checked: false,
    activeIcon: "../../../images/detail/btn_1.png",
    inactiveIcon: "../../../images/detail/btn_2.png",
    file: "",
    show: false,
    entry: [
      {
        title: "免费报名",
        text: "及时填写完整个人信息",
        img: "./image/application.png",
      },
      {
        title: "客服服务",
        text: "等待客服与您取得联系",
        img: "./image/customer .png",
      },
      {
        title: "参加面试",
        text: "按照规定时间前往面试",
        img: "./image/interview.png",
      },
      {
        title: "成功入职",
        text: "面试通过上传厂牌",
        img: "./image/entry.png",
      },
    ],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.scene) {
      const scene = this.scene(options.scene);
      wx.setStorageSync("oldUserId", scene.userId);
      wx.setStorageSync("workId", scene.workId);
      this.getUser(scene.userId, scene.workId);
      this.setData({ id: scene.workId });
    }
    if (options.id) {
      this.setData({ id: options.id });
    }
  },
  scene(e) {
    const decodeScene = decodeURIComponent(e);
    const params = {};
    decodeScene.split("&").forEach((item) => {
      const arr = item.split("=");
      params[arr[0]] = arr[1];
    });
    return params;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    await this.getid();
    await this.is_sc();
  },
  async getUser(oldUserId, workId) {
    try {
      const data = JSON.stringify({
        oldUserId,
        workId,
      });
      const res = await api.getolduser(data);
      if (res.respCode === 200) {
        const user = JSON.parse(res.source);
        wx.setStorageSync("user", user);
      }
    } catch (error) {
      err(error);
    }
  },
  async getid() {
    try {
      const { id } = this.data;
      const data = JSON.stringify({ id });
      const res = await api.work_id(data);
      if (res.respCode === 200) {
        const list = JSON.parse(res.source);
        console.log(list);
        this.setData({ list });
      }
    } catch (error) {
      err(error);
    }
  },
  async is_sc() {
    try {
      const data = JSON.stringify({
        userId: wx.getStorageSync("userId"),
        workId: this.data.id,
      });
      const res = await api.iscollect(data);
      if (res.respCode === 200) {
        let a = JSON.parse(res.source);
        if (a.result == 1) {
          this.setData({ checked: true });
        } else if (a.result == 2) {
          this.setData({ checked: false });
        }
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  onChange(e) {
    const checked = e.detail;
    this.setData({ checked });

    const data = JSON.stringify({
      userId: wx.getStorageSync("userId"),
      workId: this.data.id,
    });
    if (checked) {
      this.addcoll(data);
    } else {
      this.delcoll(data);
    }
  },
  async addcoll(data) {
    try {
      const res = await api.postcollect(data);

      if (res.respCode === 200) {
        toast("收藏成功");
      } else {
        toast("收藏失败");
      }
    } catch (error) {
      err(error);
      toast("收藏失败");
      throw error;
    }
  },
  async delcoll(data) {
    try {
      const res = await api.delcollect(data);
      if (res.respCode === 200) {
        toast("取消收藏成功");
      } else {
        toast("取消收藏失败");
      }
    } catch (error) {
      err(error);
      toast("取消收藏失败");
      throw error;
    }
  },
  async detail_share() {
    wx.showLoading({ title: "加载中" });
    try {
      const data = JSON.stringify({
        userId: wx.getStorageSync("userId"),
        workId: this.data.id,
        page: "two/pages/detail/detail",
      });
      const res = await api.work_share(data);
      if (res.respCode === 200) {
        const file = JSON.parse(res.source).filePath;
        this.setData({ file, show: true });
        wx.hideLoading();
      } else {
        toast(res.msg);
      }
    } catch (error) {
      err(error);
      wx.hideLoading();
    }
  },
  async mergeAndSaveImages() {
    const image1 = await this.getImageData(
      "https://6465-dev-9gjsl77taaa6cab5-1318959325.tcb.qcloud.la/image/fx.png"
    );
    const image2 = await this.getImageData(this.data.file);

    const query = wx.createSelectorQuery();
    query
      .select("#myCanvas")
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node;
        console.log(res);
        const ctx = canvas.getContext("2d");
        const img1 = canvas.createImage();
        const img2 = canvas.createImage();
        this.setData({
          canw: image1.width,
          canh: image1.height,
        });
        img1.src = image1.path;
        console.log(image1.path);
        img1.onload = () => {
          ctx.drawImage(img1, 0, 0, image1.width, image1.height);
          img2.src = image2.path;
          // img2.onload = () => {
          //   ctx.drawImage(img2, 56, 88, 75, 75);
          // };
        };
      });
  },
  calculateScale(imgWidth, imgHeight, desiredWidth, desiredHeight) {
    const scaleX = desiredWidth / imgWidth;
    const scaleY = desiredHeight / imgHeight;
    return Math.min(scaleX, scaleY);
  },
  getImageData(url) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: url,
        success: (res) => {
          console.log(res);
          resolve(res);
        },
        fail: (err) => {
          reject(new Error("获取图片信息失败"));
        },
      });
    });
  },
  async entry() {
    const user = wx.getStorageSync("user");
    const resp = await api.entryOrNot({
      userId: user.userId,
      workId: this.data.id,
    });
    if (resp.respCode === 200) {
      if (!user.mobile) {
        wx.showModal({
          title: "提示",
          content: "检测到您还未登录是否前往登录",
          complete: (res) => {
            if (res.confirm) {
              to("/two/login/login");
            }
          },
        });
      } else if (user.realState !== 1) {
        wx.showModal({
          title: "提示",
          content: "检测到您还未实名认证，是否前往",
          complete: (res) => {
            if (res.confirm) {
              to("/two/pages/userId/userId");
            }
          },
        });
      } else {
        const data = JSON.stringify({
          userId: user.userId,
          workId: this.data.id,
        });
        const res = await api.entry(data);
        if (res.respCode === 200) {
          toast("申请成功");
          setTimeout(() => {
            const id = JSON.parse(res.source).id;
            to("/two/enlist/enlist?id=" + id);
          }, 1500);
        } else {
          toast(res.msg);
        }
      }
    } else {
      toast(resp.msg);
    }
  },
  xx() {
    wx.getSetting({
      withSubscriptions: true,
      success: (res) => {
        const subscriptionsSetting = res.subscriptionsSetting;
        if (
          subscriptionsSetting &&
          subscriptionsSetting.mainSwitch === true &&
          subscriptionsSetting.itemSettings
        ) {
          if (
            subscriptionsSetting.itemSettings[
              "ROs_fmPI5ckSHiaCnL1zb_gNh8wMPZ-hNubwJqfsrig"
            ] === "accept"
          ) {
            console.log("开启了订阅");
          } else {
            this.getsub();
          }
        } else {
          this.getsub();
        }
      },
    });
  },
  getsub() {
    wx.showModal({
      title: "是否选择开启订阅消息",
      success: (res) => {
        console.log(res);
        if (res.confirm) {
          wx.requestSubscribeMessage({
            tmplIds: ["ROs_fmPI5ckSHiaCnL1zb_gNh8wMPZ-hNubwJqfsrig"],
            success(res) {
              console.log(res);
            },
          });
        }
      },
    });
  },
  onClose() {
    this.setData({ show: false });
  },
  // 打开高德/腾讯地图
  gotoMap() {
    const { list } = this.data;
    wx.showToast({ title: "即将跳转", icon: "none", duration: 1000 });
    // 高德地图
    wx.openLocation({
      latitude: Number(list.latitude),
      longitude: Number(list.longitude),
      address: list.interviewAddress,
      fail: (err) => {
        console.log(err);
      },
    });
  },
  imgs() {
    const { workImgList } = this.data.list;
    const src = workImgList.map((item) => item.imgUrl);
    wx.previewImage({
      urls: src,
      showmenu: true,
    });
  },
});
